package com.zeng.sys.filemd.restfulmodule.download;

import com.zeng.sys.filemd.servicemodule.service.FileRecordService;
import com.zeng.sys.filemd.servicemodule.service.FileServerService;
import com.zeng.sys.filemd.servicemodule.transfer.FileHttpTransfer;
import com.zeng.sys.filemd.servicemodule.util.MultipartFileUtil;
import com.zeng.sys.filemd.servicemodule.vo.FileRecordVo;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;

@RestController
public class DownloadController {

    @Autowired
    FileRecordService fileRecordService;

    @Autowired
    MultipartFileUtil multipartFileUtil;

    @RequestMapping
    public void download(String code, HttpServletResponse response) {
        FileRecordVo oneByCode = fileRecordService.getOneByCode(code);
        if (oneByCode == null) {
            return;
        }
        multipartFileUtil.handleFileRecordVoOnServer(oneByCode);
        byte[] download = new FileHttpTransfer(oneByCode.getFileServerVo()).download(oneByCode.getPath());
        ByteArrayInputStream input = null;
        if (download == null) {
            return;
        }
        try {
            input = new ByteArrayInputStream(download);
            IOUtils.copy(input, response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
